package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.utils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class EncodingUtil {
    public static String GBKConvertToUtf8(String s) {
        if (s != null && !(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(s))) {
            s = new String(s.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        }
        return s;
    }

    public static String convertToUtf8(String s) {
        try {
            return encodingConvert(s, StandardCharsets.UTF_8);
        } catch (UnsupportedEncodingException e) {
            return s;
        }
    }

    public static String encodingConvert(String s, Charset toEncode) throws UnsupportedEncodingException {
        final String encoding = getEncoding(s);
        if (encoding != null) {
            return new String(s.getBytes(encoding), toEncode);
        }
        return null;
    }

    public static String getEncoding(String str) {
        String encode;
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                return encode;
            }
        } catch (Exception exception) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                return encode;
            }
        } catch (Exception exception) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                return encode;
            }
        } catch (Exception exception) {
        }
        encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                return encode;
            }
        } catch (Exception exception) {
        }
        return "";
    }
}

